package cn.aylog.search;

/**
 * 二分查找
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,4,4,5,6,7,8};
        System.out.println(insertSearch(arr, 4));
    }

    /**
     * 二分查找(基本版)
     * @param arr
     * @param tar
     * @return
     */
    public static int binarySearch(int[] arr, int tar) {
        int mid = -1, len = arr.length, l = 0, r = len - 1;
        int idx = -1;
        while(l <= r) {
            mid = (l+r)/2;
            if(tar > arr[mid]) {
                l = mid + 1;
            } else if(tar < arr[mid]) {
                r = mid -1;
            } else {
                idx = mid;
                break;
            }
        }
        return idx;
    }

    /**
     * 插值查找(二分查找的优化版本)
     * @param arr
     * @param tar
     * @return
     */
    public static int insertSearch(int[] arr, int tar) {
        int len = arr.length, l = 0, r = len - 1;
        int idx = -1, mid = -1;
        while(l < r) {
            mid = l + (r-l)*(tar - arr[l])/(arr[r]-arr[l]);
            if(tar > arr[mid]) {
                l = mid + 1;
            } else if(tar < arr[mid]) {
                r = mid -1;
            } else {
                idx = mid;
                break;
            }
        }
        return idx;
    }
}
